import {Component, OnInit} from '@angular/core';
import {NzUploadFile} from 'ng-zorro-antd/upload';
import {NzMessageService} from 'ng-zorro-antd/message';
import {PpypService} from '../../ppyp.service';
import {NzCascaderOption} from 'ng-zorro-antd/cascader';
import {ActivatedRoute} from '@angular/router';
import {geti4CityNameById} from '../../../../comm';
import {UsedStorePService} from '../../../used-store/used-store-p.service';

interface TRACKMODAL {
  visible: boolean;
  loading: boolean;
  orderNum: any;
  url: string;
  remark: string;
  file: any[];
}

enum AUDITSTATE {
  '未审核',
  '已审核',
  '审核不通过'
}

enum PAYTYPE {
  '支付宝' = 1,
  '微信',
  '银联'
}

enum ORDERSTATUS {
  '有效',
  '无效',
  '待付款',
  '待审核',
  '审核不通过',
  '审核通过',
  '排队发货',
  '待发货',
  '待收货（已发货）',
  '交易完成',
  '支付超时',
  '客服取消',
  '客户取消',
  '售后中',
  '全部退货',
  '交易关闭' = 16
}


@Component({
  selector: 'app-ppyp-order-detail',
  templateUrl: './ppyp-order-detail.component.html',
  styleUrls: ['./ppyp-order-detail.component.scss']
})
export class PpypOrderDetailComponent implements OnInit {
  ORDERSTATUS = ORDERSTATUS;
  AUDITSTATE = AUDITSTATE;
  PAYTYPE = PAYTYPE;

  commodityList = [];
  orderDetail: any = {};
  expressList: any = {};
  trackList: any = [];
  trackModal: TRACKMODAL = {
    visible: false,
    loading: false,
    orderNum: '',
    url: '',
    remark: '',
    file: [],
  };
  afterSalesRefundModal = {
    visible: false,
    loading: false,
    price: null,
    remark: '',
    id: null
  };
  consigneeModal = {
    visible: false,
    name: '',
    tel: '',
    districtId: [],
    address: '',
  };
  expressModal = {
    visible: false,
    track: []
  };
  logistics = [];
  addressArea: any;
  beforeUpload = (file: NzUploadFile): boolean => {
    const acceptFileType = [
      'bmp', 'jpg', 'png', 'tif', 'gif', 'pcx', 'tga', 'exif',
      'fpx', 'svg', 'psd', 'cdr', 'pcd', 'dxf', 'ufo', 'eps',
      'ai', 'raw', 'WMF', 'webp', 'avif', 'apng', 'pdf', 'txt',
      'xls', 'xlsx', 'doc', 'docx', 'ppt', 'pptx',
    ];
    const fileName: any = file.name.split('.').pop();
    if (!acceptFileType.includes(fileName)) {
      this.nzMessageService.warning('暂不支持该文件类型');
      return false;
    }
    // @ts-ignore
    this.trackModal.file = [file];
    return false;
  };

  constructor(
    private nzMessageService: NzMessageService,
    public ppypService: PpypService,
    private activatedRoute: ActivatedRoute,
    private usedStorePService: UsedStorePService,
  ) {
  }

  ngOnInit(): void {
    import('../../../../../assets/city').then(m => {
      const op: any = m.default;
      let list = [];
      list = op.province;
      console.log(list);
      list.forEach((p: any) => {
        p.children = p?.value ? op.city[p.value] : [];
        p.children.forEach((c: any) => {
          c.children = c?.value ? op.county[c.value] : [];
        });
      });
      this.addressArea = list;
    });
    this.getOrderDetail();
    this.usedStorePService.dictData('logistics_company').then((res: any) => {
      if (res.code === 0) {
        this.logistics = res.data.list.records;
      }
    });
  }

  getTrackList(source: any) {
    this.ppypService.getTrackList({
      type: 1,
      id: this.activatedRoute.snapshot.queryParams.id,
      source,
      page: 1,
      pageSize: 9999
    }).then((res: any) => {
      console.log(res);
      if (res.code === 0) {
        this.trackList = res.data.records;
        console.log(this.trackList);
      }
    });
  }

  getOrderDetail() {
    this.ppypService.getOrderDetail(this.activatedRoute.snapshot.queryParams.id).then((res: any) => {
      if (res.code === 0) {
        this.orderDetail = res.data.order;
        this.orderDetail.list.forEach((g: any) => {
          g.price = 0;
          g.list.forEach((i: any) => {
            g.price += i.totalPrice || 0;
            if (i?.skuProperties) {
              g.type = JSON.parse(i?.skuProperties)[0].value;
            }
          });
        });
        this.expressList = res.data.orderExpress;
        this.getTrackList(this.orderDetail.source);
      }
    });
  }

  showTrackModal(orderNum: any) {
    this.trackModal.orderNum = orderNum;
    this.trackModal.visible = true;
    this.trackList = [];
    // this.ppypService.getTrackList(orderNum).then((resL: any) => {
    //   this.trackList = resL.data.records;
    // });
  }

  // 隐藏跟进模态框
  async hideTrackModal(submit: boolean) {
    if (submit) {
      if (!this.trackModal.remark) {
        this.nzMessageService.warning('请输入跟进内容');
        return;
      }
      this.trackModal.loading = true;
      if (this.trackModal.file.length) {
        const file = new FormData();
        file.append('file', this.trackModal.file[0]);
        file.append('name', (+new Date()).toString());
        await this.ppypService.fileUpload(file).then((res: any) => {
          if (res.code === 0) {
            this.trackModal.url = res.data;
          }
        });
      }
      this.ppypService.track({
        enclosure: this.trackModal.url, // 附件url
        content: this.trackModal.remark, // 跟进内容
        type: 1, // 业务类型：1-精诚图纸
      }).then((result: any) => {
        if (result.code === 0) {
          this.nzMessageService.success('操作成功');
          this.trackModal = {
            visible: false,
            loading: false,
            orderNum: '',
            url: '',
            remark: '',
            file: [],
          };
        } else {
          this.trackModal.loading = false;
          this.nzMessageService.error('操作失败');
        }
      });
    } else {
      this.trackModal = {
        visible: false,
        loading: false,
        orderNum: '',
        url: '',
        remark: '',
        file: [],
      };
    }
  }

  showAfterSalesRefundModal(id: any) {
    this.afterSalesRefundModal.visible = true;
    this.afterSalesRefundModal.id = id;
  }

  hideAfterSalesRefundModal() {
    this.afterSalesRefundModal = {
      visible: false,
      loading: false,
      price: null,
      remark: '',
      id: null
    };
  }

  refund() {
  }


  showConsigneeModal() {
    this.consigneeModal.visible = true;
  }

  hideConsigneeModal() {
    this.consigneeModal = {
      visible: false,
      name: '',
      tel: '',
      districtId: [],
      address: '',
    };
  }

  // 地区 设置默认值
  setArea(districtId: any) {
    districtId = districtId * 1;
    if (!districtId) {
      return;
    }
    this.consigneeModal.districtId = [];
    this.addressArea.forEach((p: any) => {
      p.children.forEach((c: any) => {
        c.children.forEach((m: any) => {
          if (districtId === m.value) {
            // @ts-ignore
            this.formData.districtId = [p.value, c.value, m.value];
          }
        });
      });
    });
  }

  showExpressModal(track: any) {
    if (track) {
      this.expressModal.visible = true;
      this.expressModal.track = JSON.parse(track);
    } else {
      this.nzMessageService.warning('没有找到物流信息');
    }
  }

  hideExpressModal() {
    this.expressModal.visible = false;
    this.expressModal.track = [];
  }

  cityChangeName(id: any) {
    return geti4CityNameById(id)?.name || '-';
  }

  getLogisticsName(content: any) {
    return this.logistics.filter((i: any) => i.content === content)[0]['name'];
  }
}
